package com.kecheng.action;

import com.kecheng.dao.CommonDao;
import com.kecheng.pojo.*;
import com.kecheng.util.TimeUtil;
import org.apache.struts2.ServletActionContext;
import com.kecheng.util.SpringUtil;
import com.kecheng.com.yx.util.MessageUtil;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.AllowedMethods;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoField;
import java.util.*;

import static java.time.temporal.TemporalAdjusters.nextOrSame;

/**
 * 微信支付的回调处理
 * @author yunxin
 */
@Action(value = "notify1")
@AllowedMethods(value = {("regex:.*")})
public class Notify1Action {

	private CommonDao dao = (CommonDao) SpringUtil.getBean("dao");
	@Transactional
	public String notify1() throws Exception {
		HttpServletRequest request = ServletActionContext.getRequest();
		HttpServletResponse response = ServletActionContext.getResponse();
		Map<String, String> requestMap;
		PrintWriter out = response.getWriter();

		requestMap = MessageUtil.parseXml1(request);
		String result_code = requestMap.get("result_code");
		String out_trade_no = requestMap.get("out_trade_no");
		Order order1 = new Order();
		try {
			order1.setOrderNumber(out_trade_no);
			order1 = (Order)dao.findOne(order1,"orderNumber");
		} catch (Exception e) {
			e.printStackTrace();
		}
		// order
		if (order1 != null) {
			if (result_code.equals("SUCCESS")) {
				Integer status = order1.getStatus();
				//付款成功，且订单状态未更改，做出相应的处理（订单状态,待付款:1 已付款:2）
				if (status.equals(1)) {
					//增加课时（学生课表+教师课表）
					addTeacherKeShi(order1);
					addStuKeShi(order1);
					//分销---暂无

					//更改订单状态
					order1.setPayTime(TimeUtil.getString("yyyy-MM-dd HH:mm:ss",new Date()));
					order1.setStatus(2);
					dao.update(order1);

				}
			}
			String huifu = "<xml> <return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg> </xml>";
			out.println(huifu);
			out.close();
		}
		return null;
	}

	/**
	 * 增加教师课时表
	 */
	private void addTeacherKeShi(Order order1){
		Teacher teacher = new Teacher();
		if(order1.getType()==1){
			teacher.setId(order1.getTeacherId());
			teacher = (Teacher) dao.findOne(teacher);
			//家教订单（默认从下周开始第一次家教）
			OrderDetail orderDetail = new OrderDetail();
			orderDetail.setOrderNumber(order1.getOrderNumber());
			List<OrderDetail>orderDetailList = (List<OrderDetail>)dao.find(orderDetail);

			TeacherKeShi teacherKeShi = null;
			int a = orderDetailList.size();//每周几次
			for(int i=0;i<order1.getLessonTimes();i++){
				OrderDetail orderDetail0 = orderDetailList.get(i%a);//取周几的课
				teacherKeShi = new TeacherKeShi();
				teacherKeShi.setOrderNumber(order1.getOrderNumber());
				teacherKeShi.setTeacherId(order1.getTeacherId());
				teacherKeShi.setTeacherName(teacher.getName());
				teacherKeShi.setWeekday(orderDetail0.getWeekDay());
				teacherKeShi.setDate(getStrDate(i/a+1,orderDetail0.getWeekDay()));//获取下几周的周几的日期
				teacherKeShi.setStartTime(orderDetail0.getStartTime());
				teacherKeShi.setEndTime(orderDetail0.getEndTime());
				teacherKeShi.setName(order1.getTwoClassifyName());

				dao.add(teacherKeShi);
			}
		}else{
			//报班订单（有一个开课时间）
			Banji banji = new Banji();
			banji.setId(order1.getBanjiId());
			banji = (Banji)dao.findOne(banji);

			//先查看这个老师下的课表有没有这个班级的课，如果有，就不重复添加咯
			TeacherKeShi teacherKeShi0 = new TeacherKeShi();
			teacherKeShi0.setBanjiId(banji.getId());
			List<TeacherKeShi>teacherKeShis = (List<TeacherKeShi>)dao.find(teacherKeShi0);
			if(teacherKeShis==null||teacherKeShis.size()==0){
				return;
			}

			//添加课程表
			teacher.setId(banji.getTeacherId());
			teacher = (Teacher) dao.findOne(teacher);

			BanjiDetail banjiDetail = new BanjiDetail();
			banjiDetail.setBanjiId(order1.getBanjiId());
			List<BanjiDetail>banjiDetailList = (List<BanjiDetail>)dao.find(banjiDetail);

			TeacherKeShi teacherKeShi = null;
			int a = banjiDetailList.size();//每周几次
			//开课时间
			String startDate = banji.getStartDate();//开课日期，比如03-13
			//判断当前开课日期在本周是第几天，然后周几是第一次上课，计算在开始的这个周，推了几节课
			int b = computePushClassNum(startDate,banjiDetailList);//推的次数

			for(int i=b;i<banji.getStudyWeekNum()+b;i++){
				BanjiDetail banjiDetail0 = banjiDetailList.get(i%a);
				teacherKeShi = new TeacherKeShi();
				teacherKeShi.setBanjiId(order1.getBanjiId());
				teacherKeShi.setOrderNumber(order1.getOrderNumber());
				teacherKeShi.setTeacherId(order1.getTeacherId());
				teacherKeShi.setTeacherName(teacher.getName());
				teacherKeShi.setWeekday(banjiDetail0.getWeekDate());
				teacherKeShi.setDate(getStrDate(i/a+1,banjiDetail0.getWeekDate()));
				teacherKeShi.setStartTime(banjiDetail0.getStartTime());
				teacherKeShi.setEndTime(banjiDetail0.getEndTime());
				teacherKeShi.setName(banji.getTwoClassifyName());

				dao.add(teacherKeShi);
			}

		}

	}

	/**
	 * 判断当前开课日期在本周是第几天，然后周几是第一次上课，计算在开始的这个周，推了几节课
	 * @param startDate 开始日期
	 * @param banjiDetailList 每周上课的集合
	 * @return
	 */
	private int computePushClassNum(String startDate,List<BanjiDetail>banjiDetailList){
		int b = 0;
		LocalDate date = LocalDate.parse(startDate);
		int weekOfMonth = date.get(ChronoField.ALIGNED_WEEK_OF_MONTH)+1; // 获取开始日期在本周的周几
		List<String> week = Arrays.asList("周一","周二","周三","周四","周五","周六","周日");
		for(BanjiDetail banjiDetail:banjiDetailList){
			if(week.indexOf(banjiDetail.getWeekDate())+1<weekOfMonth){
				b++;
			}
		}
		return b;
	}
	/**
	 * 根据下几周，周几来确定日期，返回比如2019-03-16
	 * @param weekNum
	 * @param weekDay
	 * @return
	 */
	private String getStrDate(Integer weekNum,String weekDay){
		DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd");
		List<String> week = Arrays.asList("周一","周二","周三","周四","周五","周六","周日");
		LocalDate dateNow = LocalDate.now();
		dateNow = dateNow.with(nextOrSame(DayOfWeek.of(week.indexOf(weekDay)+1)));
		for(int i=1;i<weekNum;i++){
			dateNow = dateNow.plusWeeks(1);
		}
		return dtf.format(dateNow);
	}

	/**
	 * 增加学生课时表
	 */
	private void addStuKeShi(Order order1){
		Team stu = new Team();
		stu.setOpenid(order1.getBuyerid());
		stu = (Team)dao.findOne(stu,"openid");

		if(order1.getType()==1){
			//家教订单（默认从下周开始第一次家教）
			OrderDetail orderDetail = new OrderDetail();
			orderDetail.setOrderNumber(order1.getOrderNumber());
			List<OrderDetail>orderDetailList = (List<OrderDetail>)dao.find(orderDetail);

			KeShi stuKeshi = null;
			int a = orderDetailList.size();//每周几次
			for(int i=0;i<order1.getLessonTimes();i++){
				OrderDetail orderDetail0 = orderDetailList.get(i%a);//取周几的课
				stuKeshi = new KeShi();
				stuKeshi.setOrderNumber(order1.getOrderNumber());
				stuKeshi.setTeacherId(order1.getTeacherId());
				stuKeshi.setStudentName(stu.getName());
				stuKeshi.setWeekday(orderDetail0.getWeekDay());
				stuKeshi.setDate(getStrDate(i/a+1,orderDetail0.getWeekDay()));//获取下几周的周几的日期
				stuKeshi.setStartTime(orderDetail0.getStartTime());
				stuKeshi.setEndTime(orderDetail0.getEndTime());
				stuKeshi.setName(order1.getTwoClassifyName());

				dao.add(stuKeshi);
			}
		}else{
			//报班订单（有一个开课时间）
			Banji banji = new Banji();
			banji.setId(order1.getBanjiId());
			banji = (Banji)dao.findOne(banji);

			BanjiDetail banjiDetail = new BanjiDetail();
			banjiDetail.setBanjiId(order1.getBanjiId());
			List<BanjiDetail>banjiDetailList = (List<BanjiDetail>)dao.find(banjiDetail);

			KeShi stuKeshi = null;
			int a = banjiDetailList.size();//每周几次
			//开课时间
			String startDate = banji.getStartDate();//开课日期，比如03-13
			//判断当前开课日期在本周是第几天，然后周几是第一次上课，计算在开始的这个周，推了几节课
			int b = computePushClassNum(startDate,banjiDetailList);//推的次数

			for(int i=b;i<banji.getStudyWeekNum()+b;i++){
				BanjiDetail banjiDetail0 = banjiDetailList.get(i%a);
				stuKeshi = new KeShi();
				stuKeshi.setOrderNumber(order1.getOrderNumber());
				stuKeshi.setTeacherId(order1.getTeacherId());
				stuKeshi.setStudentName(stu.getName());
				stuKeshi.setWeekday(banjiDetail0.getWeekDate());
				stuKeshi.setDate(getStrDate(i/a+1,banjiDetail0.getWeekDate()));
				stuKeshi.setStartTime(banjiDetail0.getStartTime());
				stuKeshi.setEndTime(banjiDetail0.getEndTime());
				stuKeshi.setName(banji.getTwoClassifyName());
				dao.add(stuKeshi);
			}
		}
	}

}
